String类中replaceAll方法不能替换美元符号$的问题解决 | 您所在的位置:网站首页 › java replace 正则替换 › String类中replaceAll方法不能替换美元符号$的问题解决 |
原文链接: http://blog.csdn.net/wolfchou/article/details/8709783
我现在有这样一个字符串 [java] view plain copy String str = "01,02,03,10,20,$,05,06|11";
想把它里面的",$,"替换成"$",这样首先会想到replace方法,直接str.replace(",$,","$");就可以了,试了一下确实也是可行的。 后来我又想如果str中有多个",$,"需要替换,只要改成replaceAll应该是不成问题的,我试了一下将str改为: [java] view plain copy String str = "01,02,$,03,10,20,$,05,06|11"; str.replaceAll(",$,","$");
这样却不生效了,一个都没有替换。 最后网上查了一下,改为: [java] view plain copy str.replaceAll( Matcher.quoteReplacement(",$,"), Matcher.quoteReplacement("$")) 就可以了。
代码str.replaceAll(a,b),如果b字符串中含有反斜杠 (/) 和美元符号 ($),则会抛出异常。 需要使用Matcher.quoteReplacement(Java.lang.String)对字符串b进行处理,即: str.replaceAll(a,Matcher.quoteReplacement(b)) 以下为JDK1.6 API说明:
replaceAll public String replaceAll(String regex, String replacement) 使用给定的 replacement 替换此字符串所有匹配给定的正则表达式的子字符串。 调用此方法的 str.replaceAll(regex, repl) 形式与以下表达式产生的结果完全相同: Pattern.compile(regex).matcher(str).replaceAll(repl) 注意,在替代字符串中使用反斜杠 (/) 和美元符号 ($) 与将其视为字面值替代字符串所得的结果可能不同;请参阅 Matcher.replaceAll。如有需要,可使用 Matcher.quoteReplacement(java.lang.String) 取消这些字符的特殊含义。 参数: regex - 用来匹配此字符串的正则表达式 replacement - 用来替换每个匹配项的字符串 返回: 所得 String 抛出: PatternSyntaxException - 如果正则表达式的语法无效 从以下版本开始: 1.4 另请参见: Pattern Matcher.quoteReplacement(",$,"), Matcher.quoteReplacement("$")
|
CopyRight 2018-2019 实验室设备网 版权所有 |